import ElementUI from 'element-ui';
import NProgress from 'nprogress'; // 加载条
import Storage from '@/global/storage';
import 'nprogress/nprogress.css';

export default {
    /**
     * 路由重定向
     * @param {*} router 路由
     */
    redirectRoutes(router) {
        const TOKEN = Storage.get("token");
        router.beforeEach((to, from, next) => {
            /* 未登录 */

            if (!TOKEN && to.name != "Login") {
                next({ name: "Login", replace: true });
                return;
            }

            /* 已登录 */
            if (TOKEN && to.name === "Login") {
                next({ name: "Home", replace: true });
                return;
            }
            if (TOKEN && to.name === "Root") {
                next({ name: "Home", replace: true });
                return;
            }

            document.title = "黎三少"
            // if (to.meta.title) {
            //     document.title = to.meta.title
            // }

            next();
        });
    },

    /**
     * 加载样式
     * @param {*} router 路由
     */
    loadStyle(router) {
        let loadingInstance = '';

        router.beforeEach((to, from, next) => {
            if (to.name === 'Login' || to.name === 'Root') {
                next();
                return false;
            }

            // 每次点击前看是否存在未关闭等待条，有就关掉，重新创建
            loadingInstance && loadingInstance.close();

            loadingInstance = ElementUI.Loading.service({
                fullscreen: true,
                background: '#ffffff',
                customClass: 'el-layout-right-loading',
                target: document.querySelector('#app-router')
            });

            // 开启加载条
            NProgress.start();

            next();
        });

        router.afterEach((to) => {
            if (to.name === 'Login' || to.name === 'Root') {
                return false;
            }

            // 延迟500毫秒关闭等待条
            setTimeout(() => {
                loadingInstance.close();
            }, 500);

            // 关闭加载条
            NProgress.done();
        });

    }
}